﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Project.Yan.Net.Models;
using Project.Yan.Net.Tool.Ex;
using Project.Yan.Net.Tool.Log;
using System.Threading.Tasks;
namespace Project.Yan.Net.Filters
{
    public class GlobalExceptionMiddleware: IExceptionFilter
    {
        private readonly ILoggerService _logger;
        public GlobalExceptionMiddleware(ILoggerService logger)
        {
            _logger =logger;
        }
        public void OnException(ExceptionContext context)
        {
            if (context.Exception is DataAccessException ex)
            {
                // 捕获领域层/应用层抛出的异常
                context.Result = new JsonResult(ApiResponse<object>.Fail(ex.Code, ex.Message));
                context.HttpContext.Response.StatusCode = 500; // BadRequest
                _logger.LogError(context.Exception.Message, context.Exception.InnerException ?? context.Exception);
            }
            else if (context.Exception is BusinessException bEx)
            {
                // 捕获领域层/应用层抛出的异常
                context.Result = new JsonResult(ApiResponse<object>.Fail(bEx.Code, bEx.Message));
                context.HttpContext.Response.StatusCode = 1000; // BadRequest
                //不输出到日志，给客户端提示
            }
            else
            {
                // 系统级异常处理
                context.Result = new JsonResult(ApiResponse<object>.Fail(CodeEnums.服务错误, "系统错误"));
                context.HttpContext.Response.StatusCode = 500;
                //输出到日志
                _logger.LogError($"{context.Exception.Message}", context.Exception.InnerException ?? context.Exception);
            }
            context.ExceptionHandled = true;
        }
    }
}
